import './assets/main.css'

import { createApp } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'
import App from './App.vue'
import { useUserStore } from './stores/user'

// 导入页面组件
import Login from './views/Login.vue'
import Register from './views/Register.vue'
import Home from './views/Home.vue'
import ContactView from './views/contact-views/ContactView.vue'

// 路由配置
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/contact',
    component: ContactView,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  console.log('路由守卫 - 目标路径:', to.path)
  console.log('路由守卫 - 当前登录状态:', userStore.isLoggedIn.value)
  console.log('路由守卫 - 用户信息:', userStore.userInfo)

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn.value) {
    // 如果需要登录但用户未登录，重定向到登录页
    console.log('路由守卫 - 需要登录，重定向到 /login')
    next('/login')
  } else if (to.path === '/login' && userStore.isLoggedIn.value) {
    // 如果已登录用户访问登录页，重定向到首页
    console.log('路由守卫 - 已登录用户访问登录页，重定向到 /home')
    next('/home')
  } else {
    console.log('路由守卫 - 允许访问:', to.path)
    next()
  }
})

const app = createApp(App)

app.use(Antd)
app.use(router)

// 初始化用户状态
const userStore = useUserStore()
userStore.initFromStorage()

app.mount('#app')
